from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class LoginForm(forms.Form):

    username = forms.CharField(
        max_length=11,
        label='请输入您的手机号',
        widget=forms.TextInput(
            attrs={
                'class': 'layui-input',
                'placeholder': '请输入您的手机号',
                'lay-verity': 'required|phone',
                'id': 'username'
            }
        )
    )
    password = forms.CharField(
        max_length=20,
        label='请您输入密码',
        widget=forms.PasswordInput(
            attrs={
                'class': 'layui-input',
                'placeholder': '请您输入密码',
                'lay-verity': 'required|password',
                'id': 'password'
            }
        )
    )

    def clean_username(self):

        username = self.cleaned_data['username']
        if len(username) == 11:
            return username
        else:
            raise ValidationError('用户名为手机号')


class LoginModelForm(forms.ModelForm):

    class Meta:

        model = User
        fields = ('username', 'password')
        labels = {
            'username': '请输入您的手机号',
            'password': '请输入您的密码',
        }
        error_messages = {
            '__all__':{
                'required': '请输入内容',
                'invalid': '请检查输入内容'
            },
        }
        widgets = {
            'username': forms.widgets.TextInput(
                attrs={
                    'class': 'layui-input',
                    'placeholder': '请输入您的手机号',
                    'lay-verify': 'required|phone',
                    'id': 'username'
                }
            ),
            'password': forms.widgets.PasswordInput(
                attrs={
                    'class': 'layui-input',
                    'placeholder': '请输入您的密码',
                    'lay-verify': 'required|password',
                    'id': 'password'
                }
            )
        }

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) == 11:
            return username
        else:
            raise ValidationError('用户名为手机号')